<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import PageHeader from "@/views/Common/PageHeader.vue";
import GoodsImg from "@/views/Detail/goodsImg.vue";
import CustomerServiceChat from "@/components/CustomerServiceChat.vue";
import {RegionFullText} from "v-region";
import {useAddressStore} from "@/stores/address.js";
import {useUserStore} from '@/stores/user'
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import { useRouter} from 'vue-router';
import {getGoodsDetailAPI} from '@/apis/goods'

const addressValue = ref('')
const addressList = useAddressStore().addressList
const cart=useUserStore().getCart()

const gotoHome = () =>{
  router.push('/homepage')
}

onMounted(()=>{
  const router = useRouter()
  getGoodsDetail(router.currentRoute.value.params.id)
  useUserStore().favorites.forEach((item,index)=>{
    if(item.gid.toString()===router.currentRoute.value.params.id){
      favoriteActive.value=true
      return
    }
  })
})

const goods=ref({})
const buyAmount=ref(1)

const getGoodsDetail=async (gid)=>{
  const res = await getGoodsDetailAPI(gid)
  console.log(res)
  goods.value=res
  if(res.goodsImg===null){
    goods.value.goodsImg=['https://tse2-mm.cn.bing.net/th/id/OIP-C.UB6gLcNB_TS5b2HhPX0lHQHaHa?w=180&h=180&c=7&r=0&o=5&dpr=1.8&pid=1.7']
  }
}

function subCount() {
  if(buyAmount.value>1){
    buyAmount.value--
  }else{
    ElMessage({
      message: '购买数量不能少于1',
      type: 'warning',
    })
  }
}

const directBuy=()=>{
  if(!useUserStore().isLogin){
    ElMessage({
      type:'warning',
      message:'请先登录'
    })
    return
  }
  const goodsData=[
    {
      shopId:goods.value.shopId,
      shopName:goods.value.shopName,
      goods:[
        {
          gid:goods.value.gid,
          img:goods.value.goodsImg[0],
          title:goods.value.title,
          price:goods.value.price,
          amount:buyAmount.value
        }
      ],
      notes:''
    }
  ]


  router.push({
    name:'userOrder',
    params:{
      goods:JSON.stringify(goodsData),
      address:addressValue.value
    }
  })
}

function addToCart() {
  if(!useUserStore().isLogin){
    ElMessage({
      type:'warning',
      message:'请先登录'
    })
    return
  }
  const goodsData=
    {
      shopId:goods.value.shopId,
      shopName:goods.value.shopName,
      checked:true,
      goods:[
        {
          gid:goods.value.gid,
          img:goods.value.goodsImg[0],
          tags:goods.value.tags,
          title:goods.value.title,
          price:goods.value.price,
          amount:buyAmount.value,
          checked:true
        }
        ]
    }


  if(cart.value.length===0){
    cart.value.push(goodsData)
  }else{
    let shopIsHave=false
    cart.value.forEach((shop,index1)=>{
      if(shop.shopId===goodsData.shopId){
        shopIsHave=true
        if(shop.goods.length===0){
          shop.goods.push(goodsData.goods)
        }else{
          let goodsIsHave=false
          shop.goods.forEach((goods,index2)=>{
            if(goods.gid===goodsData.goods[0].gid){
              goodsIsHave=true
              shop.goods[index2].amount+=goodsData.goods[0].amount
              //break
            }
          })
          if(!goodsIsHave){
            shop.goods.push(goodsData.goods[0])
          }
        }
      }
    })
    if(!shopIsHave){
      cart.value.push(goodsData)
    }
  }
  ElMessage({
    type:'success',
    message:'已加入购物车'
  })
  console.log(cart.value)
}
const favoriteActive=ref(false)
const chatDialogVisible = ref(false)

function favorite() {
  if(!useUserStore().isLogin){
    ElMessage({
      type:'warning',
      message:'请先登录'
    })
    return
  }
  if(favoriteActive.value){
    useUserStore().favorites=useUserStore().favorites.filter(item=>item.gid!==goods.value.gid)
    favoriteActive.value=false
  }else{
    useUserStore().favorites.push(goods.value)
    favoriteActive.value=true
  }
}

// 联系客服
function contactCustomerService() {
  if(!useUserStore().isLogin){
    ElMessage({
      type:'warning',
      message:'请先登录'
    })
    return
  }
  chatDialogVisible.value = true
}

</script>

<template>
  <div class="header"><page-header></page-header></div>
  <div class="logo">
    <img @click="gotoHome" style="height: 60px;width: auto;margin-left: 40px;margin-top: 20px" src="../../assets/SAS-logo.png" alt="">
  </div>

  <div class="detailPage">

    <div class="shopTitle">
      <img @click="router.push(`/shop/${goods.shopId}`)" :src="goods.shopAvatar" style="width: 45px;height: 45px" alt="">
      &nbsp;
      <span class="shopName" @click="router.push(`/shop/${goods.shopId}`)">{{goods.shopName}}</span>
      &nbsp; &nbsp;
      <div class="shopTags">
        <el-tag type="danger">
          5.0 | <el-icon><StarFilled /></el-icon>
          <el-icon><StarFilled /></el-icon>
          <el-icon><StarFilled /></el-icon>
          <el-icon><StarFilled /></el-icon>
          <el-icon><StarFilled /></el-icon></el-tag>

        <el-tag type="info" style="color: #50607a">平均11小时发货</el-tag>
        <el-tag type="info" style="color: #50607a">客服平均35秒回复</el-tag>
      </div>
      <div class="shopBtn">
        <el-button style="color: #121a2f" @click="contactCustomerService"><el-icon style="color: #008bfd"><Headset /></el-icon>&nbsp;联系客服</el-button>
        <el-button style="color: #121a2f" @click="router.push(`/shop/${goods.shopId}`)"><el-icon><Goods /></el-icon>&nbsp;进入店铺</el-button>
      </div>
    </div>

    <div class="detail">

      <div class="goodsImgs">
        <goods-img :images="goods.goodsImg"></goods-img>
      </div>

      <div class="goodsDesc">
        <span class="goodsTitle" style="font-size: 20px;font-weight: bold">
          {{goods.title}}</span>

        <div>
          <span style="font-size: 16px;color: #7c889c;margin-right: 10px"
                v-for="tag in goods.tags">{{tag}}</span>
        </div>

        <span style="color:rgb(255, 80, 0);font-weight: bold; font-size: 16px;">
          ¥<span class="price" style="font-size: 28px;(255, 80, 0)">
          {{goods.price}}
        </span>
        </span>
        <el-tag style="width: 70px;font-size: 14px" type="danger" size="large">全网低价</el-tag>

        <el-descriptions
            :column="1"
            size="large"
            :style="blockMargin"
        >
          <el-descriptions-item >
            <template #label><span class="descLabel">产&nbsp;&nbsp;&nbsp;地：</span></template>
            <RegionFullText separator=" " v-model="goods" />&nbsp;
          </el-descriptions-item>
          <el-descriptions-item >
            <template #label><span class="descLabel">配送至：</span></template>

            <el-select v-model="addressValue" placeholder="请选择" style="width: 240px">
              <template #header>
                <span style="font-size: 16px;font-weight: bold">选择配送地址</span>
                <el-button style="margin-left: 170px" @click="router.push('/userCenter/address');">添加地址</el-button>
              </template>
              <template #label>
                <RegionFullText separator="-" v-model="addressList[addressValue]" />&nbsp;
              </template>
              <el-option
                  v-for="(item,index) in addressList"
                  :key="item.aid"
                  :value="index"
                  style="height: 80px;width: 400px"
              >
                <template #default>
                    <span style="font-weight: bold" >{{ item.receiver_name }}</span>&nbsp;
                    <span>{{ item.phoneNumber }}</span>
                    <span v-show="item.isDefault" style="float: right"><el-tag type="warning">默认地址</el-tag></span><br>
                    <RegionFullText separator="" v-model="addressList[index]" />&nbsp;
                    <span>{{ item.address }}</span>
                </template>
              </el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template #label><span class="descLabel">规&nbsp;&nbsp;&nbsp;格：</span></template>
            <el-radio-button label="默认" value="default" />
          </el-descriptions-item>
          <el-descriptions-item >
            <template #label><span class="descLabel">数&nbsp;&nbsp;&nbsp;量：</span></template>
            <el-input v-model="buyAmount" style="width: 130px;">
              <template #prepend><el-button @click="subCount">-</el-button> </template>
              <template #append><el-button @click="buyAmount++">+</el-button> </template>
            </el-input>
          </el-descriptions-item>
        </el-descriptions>

        <el-button-group v-show="useUserStore().myShop===null||goods.shopId!==useUserStore().myShop.shopId">
          <el-button class="buyBtn" type="primary" @click="directBuy">立即购买</el-button>
          <el-button class="cartBtn" type="primary" @click="addToCart">加入购物车</el-button>
        </el-button-group>

        <div class="favorite" :style="{color:favoriteActive?'#00a4fd':'#000'}" @click="favorite"  v-show="useUserStore().myShop===null||goods.shopId!==useUserStore().myShop.shopId">
          <el-icon size="25" ><Star /></el-icon>
          <span style="font-size: 16px;">{{favoriteActive?'已收藏':'收藏'}}</span>
        </div>
        <el-button v-show="useUserStore().myShop!==null&&goods.shopId===useUserStore().myShop.shopId"
        style="width: 400px;height: 40px;border-radius: 10px;background-color: rgba(218,218,218,0.76);color: white">不能购买自己的商品</el-button>
      </div>
    </div>
  </div>

  <!-- 联系客服聊天对话框 -->
  <CustomerServiceChat 
    v-model="chatDialogVisible"
    :shop-id="goods.shopId"
    :shop-name="goods.shopName"
    @close="chatDialogVisible = false"
  />

</template>

<style scoped lang="less">
.detailPage{
  width: 100%;
  height: 900px;
  background-color: #f3f6f8;

  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content:  flex-start;
  align-items: center;
  align-content: stretch;
  gap: 5px
}

.header{
  width: 100%;
  height: 30px;
}
.logo{
  width: 100%;
  height: 100px;
  background-color: #f3f6f8;
}
.shopTitle{
  padding: 10px;
  margin-top: 20px;

  width: 1300px;
  height: 65px;
  background-color: #ffffff;
  border-radius: 10px;

  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  align-content: stretch;
}

.shopName{
  font-weight: bold;
  font-family: "Microsoft YaHei", serif;
  color: #11192d;
  font-size: 16px;
}

.shopName:hover{
  cursor: pointer;
  color: #39bf3e;
}

.shopTags{
  display: flex;
  flex-direction: row;
  gap: 10px;
}


.favorite:hover{
  color: #00a4fd;
  cursor:pointer
}



.shopBtn{
  margin-left: auto;
}

.detail{
  margin-top: 10px;
  width: 1300px;
  height: 600px;
  background-color: #ffffff;
  border-radius: 10px;

  padding: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: stretch;
  align-content: stretch;
  gap: 50px;
}

.goodsImgs{
  width: 600px;
  height: 550px;
  //background-color: #39bf3e;
}

.goodsDesc{
  width: 600px;
  height: 550px;
  //background-color: #ea7128;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;
  gap: 10px
}
.descLabel{
  line-height: 40px;
  color: #7c889c;
  font-size: 16px;
}

.el-button-group{
  .el-button{

    font-size: 16px;
    font-weight: bold;
    width: 240px;
    height: 50px;
    --el-button-border-color:#fff
  }
}


.cartBtn{
  border-radius: 10px;
  background-color:  rgb(255, 119, 0);
}

.buyBtn{
  border-radius: 10px;
  background-color:  rgb(255, 73, 0);

}


</style>